import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

class Solution {
    //解法1:BFS
    public List<List<Integer>> levelOrder(TreeNode root) {
        //创建一个二维数组列表,存储树所有节点
        List<List<Integer>> list = new ArrayList();
        //树为空则返回空列表
        if (root == null) return list;
        //创建辅助队列
        Deque<TreeNode> deque = new LinkedList();
        //根节点入队列
        deque.offer(root);
        //遍历树
        while (!deque.isEmpty()) {
            //创建一维数组列表记录每一层节点信息
            List<Integer> list1 = new ArrayList();
            //记录当前层数节点个数
            int size = deque.size();
            //遍历当前层节点,若该层节点左右孩子存在,则加入队列
            for(int i = 0; i < size; i++) {
                TreeNode node = deque.poll();
                //将当前层节点存储
                list1.add(node.val);
                if (node.left != null) deque.offer(node.left);
                if (node.right != null) deque.offer(node.right);
            }
            //每层节点存储完成后,二维数组列表添加该一维数组列表
            list.add(list1);
        }
        return list;
    }
    //解法2:DFS
    //public List<List<Integer>> levelOrder2(TreeNode root) {
        //List<List<Integer>> list = new ArrayList<>();
        //if (root == null) return list;

    //}
}